package com.dex4d.ui.qr;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.dex4d.R;
import com.dex4d.ui.demo.HomeActivity;
import com.dex4d.ui.qr.utils.QRCodeDecoder;
import com.king.zxing.CaptureActivity;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 扫码
 */
public class EasyCaptureActivity extends CaptureActivity implements EasyPermissions.PermissionCallbacks {

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, EasyCaptureActivity.class);
        activity.startActivityForResult(intent, HomeActivity.REQUEST_CODE_SCAN);
    }

    public static final int REQUEST_CODE_PERM = 0X03;
    public static final int REQUEST_CODE_PHOTO = 0X04;

    @BindView(R.id.ivFlash)
    ImageView ivFlash;

    @BindView(R.id.back)
    ImageView back;

    @BindView(R.id.menu_album)
    TextView menuAlbum;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        ButterKnife.bind(this);
        getBeepManager().setPlayBeep(true);
        getBeepManager().setVibrate(true);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_easy_capture;
    }


    private void offFlash() {
        Camera camera = getCameraManager().getOpenCamera().getCamera();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
        camera.setParameters(parameters);
    }

    public void openFlash() {
        Camera camera = getCameraManager().getOpenCamera().getCamera();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(parameters);
    }

    private void clickFlash(View v) {
        if (v.isSelected()) {
            offFlash();
            v.setSelected(false);
        } else {
            openFlash();
            v.setSelected(true);
        }
    }

    @OnClick(R.id.ivFlash)
    public void flash() {
        clickFlash(ivFlash);
    }

    @OnClick(R.id.back)
    public void backClick() {
        finish();
    }


    private static final String[] READ_AND_WRITE_STORAGE =
            {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};


    @AfterPermissionGranted(REQUEST_CODE_PERM)
    @OnClick(R.id.menu_album)
    public void albumClick() {
        if (hasReadAndWritePermissions()) {
            // Have permissions, do the thing!

            Matisse.from(EasyCaptureActivity.this)
                    .choose(MimeType.ofImage(), false)
                    .countable(true)
                    .maxSelectable(1)
                    .capture(false)
                    .countable(false)
                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f)
                    .imageEngine(new GlideEngine())
                    .theme(R.style.Matisse_Dracula)
                    .forResult(REQUEST_CODE_PHOTO);

        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    null,
                    REQUEST_CODE_PERM,
                    READ_AND_WRITE_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {

            if (requestCode ==REQUEST_CODE_PHOTO) {//选择图片
                if (data != null) {
                    List<String> paths = Matisse.obtainPathResult(data);
                    if (!paths.isEmpty())
                        new DecoderTask(this).execute(paths.get(0));
                }
            }

        }
    }

    protected void setImmerseLayout(View view) {// view为标题栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            int statusBarHeight = getStatusBarHeight(this.getBaseContext());
            view.setPadding(0, statusBarHeight, 0, 0);
        }
    }

    public int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    /**
     * 判断是否有读写文件夹权限
     *
     * @return
     */
    private boolean hasReadAndWritePermissions() {
        return EasyPermissions.hasPermissions(this, READ_AND_WRITE_STORAGE);
    }

    static class DecoderTask extends AsyncTask<String, Integer, String> {

        Activity activity;

        public DecoderTask(Activity activity) {
            this.activity = activity;
        }

        @Override
        protected String doInBackground(String... strings) {
            return QRCodeDecoder.syncDecodeQRCode(strings[0]);
        }

        @Override
        protected void onPostExecute(String resultString) {
            super.onPostExecute(resultString);
            Intent intent = new Intent();
            intent.putExtra(KEY_RESULT,resultString);
            activity.setResult(RESULT_OK,intent);
            activity.finish();
        }
    }

}
